//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "ioc\exec.sqf"
#include <core_macros.h>

TRACE_1("Start",_this);

private ["_namespace","_event","_params","_idx","_evt_idx","_events","_handlers","_i","_handler","_result","_partial","_handler_name"];
DEFAULT_PARAM(_namespace,0,"");
DEFAULT_PARAM(_event,1,"");
DEFAULT_PARAM(_params,2,[]);
_result = [];
if (_namespace != "" && {_event != ""}) then {
	_idx = GVAR(NAMESPACES) find toLower(_namespace);
	if (_idx >= 0) then {
		_events = GVAR(EVENTS) select _idx;
		TRACE_1("Found Namespace",ARR_3(_namespace,_idx,count _events));
		_evt_idx = _events find toLower(_event);
		if (_evt_idx >= 0) then {
			_handlers = ((GVAR(HANDLERS) select _idx) select _evt_idx);
			TRACE_1("Found Event",ARR_4(_namespace,_event,_evt_idx,_handlers));
			if (IS_ARRAY(_handlers)) then {
				for "_i" from 0 to ((count _handlers) - 1) step 1 do {
					_handler = _handlers select _i;
					if (IS_STRING(_handler)) then {
						_handler_name = _handler;
					} else {
						_handler_name = _handler select 1;
					};
					TRACE_1("Handler Name",ARR_2(_handler_name,(isNil {missionNamespace getVariable _handler_name})));
					if !(isNil {missionNamespace getVariable _handler_name}) then {
						_partial = [_event,_params] call (missionNamespace getVariable _handler_name);
						if !(isNil "_partial") then {
							TRACE_1("Partial result",_partial);
							if (IS_ARRAY(_partial)) then {
								{ _result set[count _result,_x];
								}foreach _partial;
							} else {
								_result set[count _result,_partial];
							};
						} else {
							TRACE_1("No result",ARR_3(_namespace,_event,_i));
						};
					} else {
						DEBUG_1("Handler not found",_handler_name);
					};
				};
			} else {
				DEBUG_1("Invalid Handlers",_this);
			};
		} else {
			DEBUG_1("Invalid Event",_this);
		};
	} else {
		DEBUG_1("Invalid Namespace",_this);
	};
} else {
	DEBUG_1("Invalid Event",_this);
};

TRACE_1("End",count _result);
_result;